package com.dfrz.problem.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dfrz.problem.dao.SysAdminDao;
import com.dfrz.problem.model.SysAdmin;
import com.dfrz.problem.utils.MD5Util;

public class SysAdminDaoImpl implements SysAdminDao {
	private static final Logger logger = LoggerFactory.getLogger(SysAdminDaoImpl.class);
	
	SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public SysAdmin getSysAdmin(String email) {
		if(getSession().createQuery("FROM SysAdmin").list().size() == 0){
			getSession().saveOrUpdate(new SysAdmin("admin@163.com",MD5Util.getMD5Str("123456"),"admin"));
			logger.debug("默认唯一系统管理员账户：admin@163.com  密码：123456");
		}
		
		String hql = "FROM SysAdmin s WHERE s.adminEmail =:email";
		Query query = getSession().createQuery(hql);
		query.setParameter("email", email);
		SysAdmin sysAdmin = (SysAdmin) query.uniqueResult();
		if(sysAdmin != null){
			logger.debug("AdminName is -----> {}",sysAdmin.getAdminName());
		}
		
		return sysAdmin;
	}

	@Override
	public boolean updatePwd(String email, String pwd) {
		String hql = "FROM SysAdmin s WHERE s.adminEmail =:email";
		Query query = getSession().createQuery(hql);
		query.setParameter("email", email);
		SysAdmin sysAdmin = (SysAdmin) query.uniqueResult();
		// 该邮箱存在
		if(sysAdmin != null){
			hql = "UPDATE SysAdmin s SET s.password =:password WHERE s.adminEmail =:email";
			query = getSession().createQuery(hql);
			query.setParameter("password", pwd);
			query.setParameter("email", email);
			query.executeUpdate();
			return true;
		}
		
		return false;
	}

	@Override
	public boolean checkPwd(String password, String email) {
		String hql = "FROM SysAdmin s WHERE s.adminEmail =:email";
		Query query = getSession().createQuery(hql);
		logger.debug("验证管理员 {} 密码是否正确",email);
		query.setParameter("email", email);
		SysAdmin sysAdmin = (SysAdmin) query.uniqueResult();
		if(sysAdmin != null){
			return sysAdmin.getPassword().equals(password);
		}
		
		return false;
	}

	@Override
	public void addSysAdmin(SysAdmin admin) {
		getSession().save(admin);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysAdmin> getAllAdmin() {
		String hql = "FROM SysAdmin";
		Query query = getSession().createQuery(hql);
		return query.list();
	}

}
